<template>
  <el-row justify="center" align="middle" style="height: 100%;">
    <el-col :span="5">
      <h2 style="text-align: center;">用户注册</h2>
      <el-form ref="ruleFormRef" :model="fromData" :rules="rules" label-width="120px" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="fromData.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="fromData.password" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            注册
          </el-button>
          <el-button @click="router.push({ name: 'login' })">登录</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<script setup>
import { reactive, ref } from 'vue'
import { register } from '@/api/userApi'
import router from '@/router'
const ruleFormRef = ref()
const fromData = reactive({
  username: "",
  password: ""
})
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度为3~20', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 20, message: '长度为3~20', trigger: 'blur' },
  ],
})
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const res = await register(fromData)
      if (res.code === 10000) {
        router.push({ name: "login" })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>
<style scoped></style>
